import ChildComponent from "./ChildComponent";
import axios from 'axios';
import React, { useState, useEffect } from 'react';

function ParentComponent() {
    // 获取接口数据渲染
    const [users,setUsers] = useState([])

    const deleteUser = (id) => {
        setUsers(item => {
            const newUsers = item.filter(item => item.id !== id)
            return newUsers
        })
    }
    const addUser = () => {
      const username = document.getElementById('username').value
      const password = document.getElementById('password').value
      const user = {
          id: users.length + 1,
          username,
          password
      }
      setUsers(item => {
          const newUsers = [...item, user]
          return newUsers
      })
    }

    useEffect(()=>{
    // 请求数据
    async function getData(){
        // axio请求数据
        const res = await axios.get('http://localhost:3004/users')
        const list = await JSON.stringify(res.data)
        console.log(res.data)
        setUsers(res.data)
    }
    getData()
    }, [])

  return (
    <div>
      用户名：<input id="username" type="text" /><br />
      密码：<input id="password" type="password" /><br />
      <batton onClick={() => addUser()}>添加</batton><br />
      <ChildComponent 
      users = {users}
      deleteUser = {deleteUser} />
    </div>
  );
}

export default ParentComponent;